using Bomb;
using UnityEngine;
using UnityEngine.UI;

namespace Player
{
    public class PlayerDropBomb : MonoBehaviour
    {
        [SerializeField] private Bomb.Bomb _bombPrefab;
        [SerializeField] private int _maxBombsCount;
        [SerializeField] private Text _bombsCountText;
        [SerializeField] private Vector3 _spawnOffset;
        private Managers.StatisticManager _stats;
        private int _bombsCount;

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.F))
            {
                DropBomb();
            }
        }

        /// <summary>
        /// Сбрасывает бомбу, если у игрока осталась хотя бы одна.
        /// </summary>
        public void DropBomb()
        {
            if (_bombsCount <= 0) return;
            _bombsCount -= 1;
            UpdateBombsCountText();
            Instantiate(
                _bombPrefab,
                transform.position + _spawnOffset,
                Quaternion.identity
            );
        }

        private void OnDrawGizmosSelected()
        {
            Gizmos.DrawSphere(transform.position + _spawnOffset, 0.05f);
        }

        private void OnValidate()
        {
            if (_maxBombsCount < 1) _maxBombsCount = 1;
        }

        private void UpdateBombsCountText()
        {
            _bombsCountText.text = $"Бомб осталось: <b>{_bombsCount}</b>";
        }

        private void OnTriggerEnter(Collider other)
        {
            if (!other.TryGetComponent(out Bombs _)) return;
        
            _bombsCount = _maxBombsCount;
            UpdateBombsCountText();
        }
    }
}
